// pages/goods/list/index.js
import {
  reqGoodsList
} from "../../../api/goods"
import {
  toast
} from "../../../../../utils/extendApi";
Page({
  /**
   * 页面的初始数据
   */
  data: {
    goodsList: [], // 商品列表数据
    isFinish: false, // 判断数据是否加载完毕
    total: 0, //数据总条数
    isLoading: false,
    requestData: {
      page: 1, //页码
      limit: 10, //每页请求条数
      category1Id: "", //一级商品分类id
      category2Id: "" //二级商品分类id
    }, //商品请求参数

  },
  //获取商品列表数据
  async getGoodsList() {
    //在请求发送之前将isLoading设置为true,表示正在加载
    this.data.isLoading = true
    const {
      data
    } = await reqGoodsList(this.data.requestData);
    //请求结束以后,将isLoading设置为false表示请求已经结束
    this.data.isLoading = false
    this.setData({
      goodsList: [...this.data.goodsList, ...data.records],
      total: data.total
    })

  },
  //监听到页面上拉操作
  onReachBottom() {
    const {
      goodsList,
      total,
      requestData,
      isLoading
    } = this.data
    //解构数据
    const {
      page
    } = requestData
    //判断isLoading状态
    if (isLoading) {
      return
    }
    //开始让goodsList长度和total对比
    if (goodsList.length === total) {
      this.setData({
        isFinish: true
      })
      return
    }
    //页码加1
    this.setData({
      requestData: {
        ...this.data.requestData,
        page: page + 1
      }
    })
    //重新获取商品列表
    this.getGoodsList()
  },
  //监听页面下拉刷新操作
  onPullDownRefresh() {
    //将数据进行重置
    this.setData({
      goodsList: [],
      total: 0,
      isFinish: false,
      requestData: {
        ...this.data.requestData,
        page: 1
      }
    })
    //使用最新的参数发送请求
    this.getGoodsList()
    //手动关闭下拉刷新效果
    wx.stopPullDownRefresh()
  },
  onLoad(options) {
    //用来合并对象
    Object.assign(this.data.requestData, options)
    this.getGoodsList()
  },
  //实现转发功能
  onShareAppMessage() {

  },
  //能够把小程序分享到朋友圈
  onShareTimeline() {

  }
})